//
//  CTVUtil.m
//  mediabridge
//
//  Created by Bruno Keymolen on 21/08/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVUtil.h"
#import <stdio.h>
#import "CTVChannelPlayerController.h"

@implementation CTVUtil


+(long)fileSize:(FILE*)f
{
	long cur_pos, length;
	cur_pos = ftell(f);
	fseek(f, 0, SEEK_END); // set pointer to end of file
	length=ftell(f); // offset in bytes from file's beginning
	fseek(f, cur_pos, SEEK_SET); // restore original position
	return length;
}


/* 
 * HTTP Header Parser utils 
 */

//Range: bytes=0-65535
+(BOOL)parseHTTPHeaderRange:(NSString*)rangeString resultRange:(NSRange*)range{
	char* tmp;
	char* offset;
	
	tmp = (char*)[rangeString cStringUsingEncoding:NSASCIIStringEncoding];	
	
	//Parse range header, format: "bytes=0-1"
	//find the =
	if( (offset = strchr(tmp, '=')) == NULL){
		return FALSE;
	}
	range->location = atoi(offset+1);

	if( (offset = strchr(offset, '-')) == NULL){
		return FALSE;
	}
	range->length = (atoi(offset+1) - range->location) + 1;
	
	return TRUE;
}

//Content-Range: bytes 0-65535/23472657
+(BOOL)parseHTTPHeaderContentRange:(NSString*)rangeString resultRange:(NSRange*)range resultSize:(int*)size{
	char* tmp;
	char* offset;
	
	tmp = (char*)[rangeString cStringUsingEncoding:NSASCIIStringEncoding];	
	
	//find the s (from bytes)
	if( (offset = strchr(tmp, 's')) == NULL){
		return FALSE;
	}
	range->location = atoi(offset+1);
	
	//find the -
	if( (offset = strchr(offset, '-')) == NULL){
		return FALSE;
	}
	range->length = (atoi(offset+1) - range->location) + 1;
	
	//find the / 
	if( (offset = strchr(tmp, '/')) == NULL){
		return FALSE;
	}
	*size = atoi(offset+1);
	
	
	return TRUE;
}

//Content-Length: 65536
+(BOOL)parseHTTPHeaderContentLength:(NSString*)lengthString resultSize:(int*)size{
	char* tmp;
	char* offset;
	
	tmp = (char*)[lengthString cStringUsingEncoding:NSASCIIStringEncoding];	
	
	offset = tmp;
	
	*size = atoi(offset);
	
	return TRUE;
}



//+(NSString*)splitSecondsToDays:(*int)day hours
//
//}


//If 0, never show.
//When fullDetail = TRUE ; dhms, hms, ms, s 
//When fullDetail = FALSE ; dh, hm, m, s 
+(NSString*)getTimeRepresentationString:(int)sec fullDetail:(BOOL)fulldetail fullNames:(BOOL)fullnames{
	NSString* ret = @"";
	int d  = sec / (60 * 60 * 24);
	int ds = d * 60 * 60 * 24;
	int h  = (sec - ds) / (60 * 60);
	int hs = h * 60 * 60;
	int m  = (sec - hs - ds) / 60;
	int ms = m  * 60;
	int s  = sec - ms - hs - ds;
	
	NSString *nd, *nh, *nm, *ns;
	
	if(fullnames == TRUE){
		if(d > 1){
			nd = @" Days";
		}else{
			nd = @" Day";
		}
		if(h > 1){
			nh = @" Hours";
		}else{
			nh = @" Hour";
		}
		if(m > 1){
			nm = @" Minutes";
		}else{
			nm = @" Minute";
		}
		if(s > 1){
			ns = @" Seconds";
		}else{
			ns = @" Second";
		}
	}else{
		nd = @"D";
		nh = @"h";
		nm = @"m";
		ns = @"sec";	
	}
	
	
	//When fullDetail = TRUE ; dhms, hms, ms, s 
	if(fulldetail == TRUE){
		if(d != 0){
			ret = [NSString stringWithFormat:@"%@ %d%@", ret, d, nd];
		}
		if(h != 0){
			ret = [NSString stringWithFormat:@"%@ %d%@", ret, h, nh];
		}
		if(m != 0){
			ret = [NSString stringWithFormat:@"%@ %d%@", ret, m, nm];
		}
		if(s != 0){
			ret = [NSString stringWithFormat:@"%@ %d%@", ret, s, ns];
		}
	}else{
	//When fullDetail = FALSE ; dh, hm, m, s 
		//dh
		if(d != 0){
			ret = [NSString stringWithFormat:@"%@ %d%@", ret, d, nd];
			if(h != 0){
				ret = [NSString stringWithFormat:@"%@ %d%@", ret, h, nh];
			}			
		}
		//hm
		if(d == 0 && h != 0){
			ret = [NSString stringWithFormat:@"%@%dh", ret, h];
			if(m != 0){
				ret = [NSString stringWithFormat:@"%@%dm", ret, m];
			}
		}
		//m
		if(d == 0 && h == 0 && m != 0){
			ret = [NSString stringWithFormat:@"%@%d%@", ret, m, nm];
		}
		//s
		if(d == 0 && h == 0 && m == 0 ){
			ret = [NSString stringWithFormat:@"%@%d%@", ret, s, ns];
		}
	}
	
	return ret;
}


+(NSString*)findFileTypeExtensionForUrlString:urlString andHeaderData:(NSData*)data{
	NSString* ext;
	char* cdata;
	
	
	//Check if the URL ends with .nnn where len nnn >=3 && <=4
	NSURL* url = [NSURL URLWithString:urlString];
	NSString* path = [url path];
	ext = [path pathExtension];
	if(ext != nil){
		if([ext length] >= 3 && [ext length] <= 4){
			return ext;
		}
	}
	
	if([data length] <= 0){
		return nil;
	}
	
	//If not, check the header data
	cdata = (char*)[data bytes];
	int tel;
	
	/* FLV
	 * http://osflash.org/flv
	 */
	const char flvHeader[] = {'F','L','V',0x01}; 
	if(memcmp(cdata, flvHeader, 4) == 0){
		ext = @"flv";
		return ext;
	}
	

	/* M4V
	 */
	const char m4vHeader[] = {'M','4','V'}; 
	for(tel=0;tel<[data length]-10;tel++){
		if(memcmp(cdata+tel, m4vHeader, 3) == 0){
			ext = @"m4v";
			return ext;
		}
	}

	/* MOV
	 */
	
	  
	/* MP4
	 */
	const char mp4Header[] = {'M','P','E', 'G', '-', '4'}; 
	for(tel=0;tel<[data length]-10;tel++){
		if(memcmp(cdata+tel, mp4Header, 6) == 0){
			ext = @"mp4";
			return ext;
		}
	}
	const char mp4Header2[] = {'m','p','4'}; 
	for(tel=0;tel<[data length]-10;tel++){
		if(memcmp(cdata+tel, mp4Header2, 3) == 0){
			ext = @"mp4";
			return ext;
		}
	}
	  
	 
	/* AVI
	 */ 
	const char aviHeader[] = {'A','V','I'}; 
	for(tel=0;tel<[data length]-10;tel++){
		if(memcmp(cdata+tel, aviHeader, 3) == 0){
			ext = @"avi";
			return ext;
		}
	}
	
	
	/* DIVX
	 */
	
	
	
	return nil;
}


//Private
+(id)playClipControllerForURLString:(NSString*)urlString andScene:(id)scene{					
		NSURL* mediaURL;
		NSError *error = [[NSError alloc] init];

		NSLog( @"Play Clip: [%s]\n", [urlString UTF8String]);
					
		if( [urlString hasPrefix:@"http"] == YES  ){
			mediaURL = [NSURL URLWithString:urlString];
		}else{
			mediaURL = [NSURL fileURLWithPath:urlString];
		}

		//Asset with URL
		BRSimpleMediaAsset *asset = [[[BRSimpleMediaAsset alloc] initWithMediaURL:mediaURL] autorelease];
		
		//Player, set media asset
		id player = [[[BRQTKitVideoPlayer alloc] init] autorelease];
		[player setMedia: asset error:&error];


		//to the screen; controller, set player
		id controller = [[[BRVideoPlayerController alloc] initWithScene:scene] autorelease];
		[controller setVideoPlayer:player];
			  
		[error release];
	
		return controller;
}

+(int)getLastOccurenceOfChar:(char)character inString:(NSString*)string{
	const char* bytes = [string cStringUsingEncoding:NSASCIIStringEncoding];
	char* chars = strrchr(bytes, character);
	if(chars == NULL){
		return -1;
	}
	int pos = (int)chars - (int)bytes;
	return pos;
}


+(NSUserDefaults*)userDefaults{
	static NSUserDefaults* ctv_userdefaults = nil;
	if(ctv_userdefaults == nil){
		ctv_userdefaults = [NSUserDefaults standardUserDefaults];
	}
	return ctv_userdefaults;	
}


@end
